package com.open.center.jpa.converter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.NonNull;

import com.open.center.common.constant.Enumerator;


public class WebEnumConverter<T extends Enumerator<?, ?>> implements Converter<String, T> {

    private final Map<String, T> enums = new ConcurrentHashMap<>();

    public WebEnumConverter(Class<T> clazz) {
        T[] enumConstants = clazz.getEnumConstants();
        for (T e : enumConstants) {
            enums.put(e.getId().toString(), e);
        }
    }

    @Override
    public T convert(@NonNull String source) {
        T t = enums.get(source);
        if (t == null) {
            throw new IllegalArgumentException("没有匹配 " + source + " 的枚举类型");
        }
        return t;
    }
}
